package juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liweimin
 * @date 2021/4/23 14:34
 * @since
 */
public class LockTest {
    public static void main(String[] args) {
        Ticket1 ticket = new Ticket1();
//        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sell();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sell();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sell();
            }
        }, "C").start();
    }
}

class Ticket {
    private int number = 50;

    public void sell() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了第" + number-- + "张票，剩余" + number);
        }
    }
}

class Ticket1 {
    private int number = 50;
    //公平锁-->先来后到。默认非公平锁
    Lock lock = new ReentrantLock(true);

    public void sell() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + number-- + "张票，剩余" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}